/* ***** BEGIN LICENSE BLOCK *****
 *   Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is sudoku.
 *
 * The Initial Developer of the Original Code is
 * Petr Blahoš.
 * Portions created by the Initial Developer are Copyright (C) 2008
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 * 
 * ***** END LICENSE BLOCK ***** */

Components.utils.import("resource://sudoku/griddb.jsm");

var prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
var sudokuPrefs = prefService.getBranch("extensions.sudoku.");

var consoleService = Components.classes["@mozilla.org/consoleservice;1"]
		.getService(Components.interfaces.nsIConsoleService);
function LOG(msg) {
	consoleService.logStringMessage(msg);
}
function DUMP_MEMBERS(o) {
	var s = "" + o + " members:";
	for (var i in o) {
		s+= i + ",";
	}
	LOG(s);
}

var gridsb = {
init: function() {
	this.browser = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
	   .getInterface(Components.interfaces.nsIWebNavigation)
	   .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
	   .rootTreeItem
	   .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
	   .getInterface(Components.interfaces.nsIDOMWindow).gBrowser;

	this.strings = document.getElementById("main-strings");
	this.saved = document.getElementById("saved");
	this.item_template = document.getElementById("item_template");

	this.show_saved();
},
unload: function() {
	// called when the sidebar is hidden
},
show_saved: function() {
	while(this.saved.getRowCount()) {
		this.saved.removeItemAt(0);
	}

	var s1 = griddb.conn.createStatement("SELECT givens, date FROM saves ORDER BY date");
	while (s1.executeStep()) {
		var g = s1.getString(0);
		var d = s1.getInt64(1);
		LOG("SAVES: " + d + " " + g);
		this.add_saved(g, d);
	}
},
add_saved: function(grid, dtx) {
	var item = document.createElement("richlistitem");
	var hb = document.createElement("hbox");
	var vb = document.createElement("vbox");
	var s0;

	var dt = new Date();
	dt.setTime(dtx);

	hb.flex = 1;
	hb.align = "center";
	vb.flex = 1;

	//item.tooltip = "gridtip";
	item.id = "item_" + grid;
	
	add_desc = function(pre) {
		if (""!=temp) {
			s0 = document.createElement("description");
			if (""!=pre) {
				temp = pre + " " + temp;
			}
			s0.textContent = temp;
			vb.appendChild(s0);
		}
	};

	temp = dt.toLocaleString();
	add_desc("");

	s0 = document.createElement("image");
	s0.setAttribute("src", "chrome://sudoku/skin/main-small.png");
	hb.appendChild(s0);

	s0 = document.createElement("button");
	s0.textContent = this.strings.getString("play.btn")
	s0.addEventListener("click", function(ev) {gridsb.action(ev, grid)} , false);
	hb.appendChild(vb);
	hb.appendChild(s0);
	item.appendChild(hb);
	this.saved.appendChild(item);
},
action: function(ev, grid) {
	var uri = "chrome://sudoku/content/grid.xul?p="+grid;
	//this.browser.selectedTab = this.browser.addTab(uri);
	this.browser.openUILink(uri, ev, false, true);
	/*for (var i = 0;i<this.browser.tabContainer.childNodes.length;i++) {
		var b = this.browser.getBrowserAtIndex(i);
		LOG("TAB: " + b.currentURI.spec);
		if (0==b.currentURI.spec.indexOf("chrome://sudoku/content/grid.xul")) {
			b.currentURI = 
		}
	}*/
},
random: function(ev, difficulty) {
	var uri= "chrome://sudoku/content/grid.xul?r=" + difficulty;
	this.browser.openUILink(uri, ev, false, true);
},
tip_showing: function(ev) {
	var fvr = this.saved.getIndexOfFirstVisibleRow();
	var lvr = fvr + this.saved.getNumberOfVisibleRows() + 1;
	var found = null;
	for (var i = fvr;i<lvr;i++) {
		var r = this.saved.getItemAtIndex(i).getBoundingClientRect();
		if (ev.clientY>=r.top && ev.clientY<=r.bottom && ev.clientX>=r.left && ev.clientX<=r.right) {
			found = this.saved.getItemAtIndex(i);
			break;
		}
	}
	if (null==found) {
		return false;
	}
	if ("item_"!=found.id.substring(0, 5)) {
		return false;
	}
	var grid_id = found.id.substring(5);
	LOG("GRID_ID=" + grid_id);
	var grid = griddb.get_grid_by_id(grid_id);
	for (var i = 0;i<grid.grid.length;i++) {
		var c = grid.grid.charAt(i);
		var el = document.getElementById("g" + i);
		if ('0'==c) {
			c = '';
			el.style.font.weight = "bold";
		}
		el.value = c;
	}

	var out = "";
	var temp;

	document.getElementById("tiptext1").value = "";
	document.getElementById("tiptext2").value = "";
	document.getElementById("tiptext3").value = "";
	document.getElementById("tiptext4").value = "";
	document.getElementById("tiptext5").value = "";
	try {
		temp = "";
		if (grid.is_easy()) {
			temp = this.strings.getString("gridsidebar.easy");
		} else if (grid.is_medium()) {
			temp = this.strings.getString("gridsidebar.medium");
		} else if (grid.is_hard()) {
			temp = this.strings.getString("gridsidebar.hard");
		}
		if (""!=temp) {
			document.getElementById("tiptext1").value = this.strings.getString("difficulty.label") + " " + temp + "(" + grid.get_rating() + ")";
		}
		temp = grid.get_best_time();
		if (""!=temp) {
			document.getElementById("tiptext2").value = this.strings.getString("besttime.label") + " " + temp;
		}
		temp = grid.get_avg_time();
		if (""!=temp) {
			document.getElementById("tiptext3").value = this.strings.getString("avgtime.label") + " " + temp;
		}
		if (grid.count>0) {
			if (1==grid.count) {
				document.getElementById("tiptext4").value = this.strings.getString("wincount1.label");
			} else {
				document.getElementById("tiptext4").value = this.strings.getFormattedString("wincount.label", ["" + grid.count], 1);
			}
			temp = grid.get_date();
			if (""!=temp) {
				document.getElementById("tiptext5").value = this.strings.getFormattedString("lastwin.label", [temp], 1);
			}
		}
	} catch (e) { /*not exactly good practise*/
	}

	return true;
},
_sentinel_0: 0
};

